<template>
  <ul v-if="links!.length" class="w-full">
    <li
      v-for="link in links"
      :key="link.text"
      :class="{ 'ml-[20px]': link.depth == 3 }"
    >
      <UButton
        variant="ghost"
        class="w-full"
        color="gray"
        @click.stop="toPath(link)"
      >
        <span
          class="hover:text-primary relative truncate"
          :class="activeHeadings.includes(link.id) ? 'text-primary' : ''"
          >{{ link.text }}</span
        >
      </UButton>
      <ContentTree v-if="link.children" :links="link.children"></ContentTree>
    </li>
  </ul>
</template>

<script setup lang="ts">
interface Links {
  text: string
  id: string
  depth: number
  children?: Links[] | undefined
}
interface Props {
  links: Links[] | undefined
}
const props = defineProps<Props>()
const { links } = props
const route = useRoute()
const router = useRouter()
const curAnchorPoint = ref('')
function toPath(link: any) {
  const encodedId = encodeURIComponent(link.id)
  router.push(`#${encodedId}`)
  // router.push(route.path + '#' + link.id)
  curAnchorPoint.value = link.id
}
const { activeHeadings, updateHeadings } = useScrollspy()

const nuxtApp = useNuxtApp()
nuxtApp.hooks.hookOnce('page:finish', () => {
  console.log('page:finish')
  setTimeout(() => {
    updateHeadings([
      ...document.querySelectorAll('h2'),
      ...document.querySelectorAll('h3'),
    ])
  }, 100)

  // updateHeadings([
  //   ...document.querySelectorAll('h2'),
  //   ...document.querySelectorAll('h3'),
  // ])
})
</script>

<style scoped></style>
